from extensions.common.base import *
from extensions.models import *

from django.db import models
from django.utils import timezone
import pendulum
import re

class Plan(models.Model):
    """交易计划"""
    """交易计划"""
    number = models.CharField(max_length=32, verbose_name='编号')
    trend = models.CharField(max_length=10, choices=[('bullish', '多头'), ('bearish', '空头')], verbose_name='趋势')
    current_price = models.FloatField(verbose_name='当前价格')
    key_point = models.FloatField(verbose_name='当前关键点位')
    support_point = models.FloatField(verbose_name='支撑位')
    resistance_point = models.FloatField(verbose_name='阻力位')
    current_price_13579 = models.FloatField(verbose_name='13579', blank=True, null=True)
    sell9_buy1 = models.FloatField(verbose_name='9空1多', blank=True, null=True)
    entrance_point = models.FloatField(verbose_name='入场位')
    stop_loss_point = models.FloatField(verbose_name='止损位')
    profit_taking_point = models.FloatField(verbose_name='止盈位')
    trading_lots = models.FloatField(verbose_name='交易手数')
    expected_loss = models.FloatField(verbose_name='预计亏损', blank=True, null=True)
    expected_profit = models.FloatField(verbose_name='预计盈利', blank=True, null=True)
    profit_loss_ratio = models.FloatField(verbose_name='盈亏比', blank=True, null=True)
    time_node = models.CharField(max_length=15, verbose_name='交易时间节点')
    remark = models.CharField(max_length=256, null=True, blank=True, verbose_name='备注')
    is_void = models.BooleanField(default=False, verbose_name='作废状态')
    creator = models.ForeignKey(
            'system.User',
            on_delete=models.PROTECT,
            related_name='plans_created',
            verbose_name='创建人'
        )
    create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    update_time = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    team = models.ForeignKey(
        'system.Team',
        on_delete=models.CASCADE,
        related_name='plans',
        verbose_name='团队'
    )
    status = models.CharField(
        max_length=16,
        choices=[('pending', '待执行'), ('in_progress', '进行中'), ('completed', '已完成'), ('cancelled', '已取消')],
        default='pending',
        verbose_name='状态'
    )
    start_date = models.DateField(verbose_name='开始日期')
    end_date = models.DateField(verbose_name='结束日期')
    goal_target = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='目标金额')
    strategy_details = models.TextField(null=True, blank=True, verbose_name='策略详情')

    @classmethod
    def get_number(cls, team):
        start_date, end_date = pendulum.today(), pendulum.tomorrow()
        instance = cls.objects.filter(
            team=team,
            create_time__gte=start_date.format('YYYY-MM-DD HH:mm:ss'),
            create_time__lt=end_date.format('YYYY-MM-DD HH:mm:ss')
        ).last()

        try:
            result = re.match(r'^(.*?)([0-9]+)$', instance.number)
            number = result.group(1) + str(int(result.group(2)) + 1)
        except AttributeError:
            number = 'P' + pendulum.today().format('YYYYMMDD') + '0001'

        return number

    def __str__(self):
        return f"{self.number} - {self.status}"